﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Utility;
using System.Data;
using VAdvantage.DataBase;
using VAdvantage.Model;
using VAdvantage.Logging;
using VAdvantage.Classes;
using System.IO;
using VAdvantage.Apps;
using System.ComponentModel;
using System.Text;


namespace VAdvantage.Framework
{
    public partial class VSetup : SilverlightDesktop.Controls.Form
    {
        private int _windowNo = 0;
        private FormFrame _frame;
        OpenFileDialog fileOpen = new OpenFileDialog();
        private BackgroundWorker worker = new BackgroundWorker();
        private static VLogger log = VLogger.GetVLogger(typeof(VSetup).FullName);
      
        public VSetup()
        {
            Envs.SetBusyIndicator(true);
            InitializeComponent();
           fileOpen.Filter = "All files (*.*)|*.*";
           LayoutRoot.Background = new SolidColorBrush(GlobalVariable.WINDOW_BACK_COLOR);
            fileOpen.Multiselect = true;
            JBInit();
            DynInit();
          //  gridProgress.Visibility = Visibility.Collapsed;
            this.Title = Msg.GetMsg(Envs.GetContext(), "InitialClientSetup");
          
            
            
        }
 
        private void JBInit()
        {
            String optional = Msg.Translate(Envs.GetContext(), "Optional");
            lClientName.Content = Msg.Translate(Envs.GetContext(), "AD_Client_ID");
            //	lClientName.setToolTipText("");
            fClientName.Text = "client";
            //
            lOrgName.Content = Msg.Translate(Envs.GetContext(), "AD_Org_ID");
            fOrgName.Text = "org";
            //
            lCurrency.Content = Msg.Translate(Envs.GetContext(), "C_Currency_ID");
            //	lCurrency.setToolTipText("");
            //
            lUserClient.Content = Msg.ParseTranslation(Envs.GetContext(), "@AD_User_ID@ @AD_Client_ID@");
            //	lUserClient.setToolTipText("User name for client level access");
            fUserClient.Text = "clientAdmin";
            //
            lUserOrg.Content = Msg.ParseTranslation(Envs.GetContext(), "@AD_User_ID@ @AD_Org_ID@");
            //	lUserOrg.setToolTipText("");
            fUserOrg.Text = "clientUser";
            //
            lCountry.Content = Msg.Translate(Envs.GetContext(), "C_Country_ID");
            lCity.Content = Msg.Translate(Envs.GetContext(), "C_City_ID");
            fCity.Text = "city";
            lRegion.Content = Msg.Translate(Envs.GetContext(), "C_Region_ID");
            //
            lAccountSeg.Content = optional;

            fBPartner.IsChecked = true;
            fBPartner.Content = Msg.Translate(Envs.GetContext(), "C_BPartner_ID");

            fProduct.IsChecked = true;
            fProduct.Content = Msg.Translate(Envs.GetContext(), "M_Product_ID");

            fProject.Content = Msg.Translate(Envs.GetContext(), "C_Project_ID");
            fMCampaign.Content = Msg.Translate(Envs.GetContext(), "C_Campaign_ID");
            fSRegion.Content = Msg.Translate(Envs.GetContext(), "C_SalesRegion_ID");

            buttonLoadAcct.Content = Msg.GetMsg(Envs.GetContext(), "LoadAccountingValues");

            fileOpen.Filter = "CSV File (*.csv)|*.csv";
            fileOpen.FilterIndex = 2;
            
        }

        private void DynInit()
        {
            //	Currency
            String sql = "SELECT C_Currency_ID, Description FROM C_Currency ORDER BY 1";	//	USD first
            IDataReader dr = null;
            String sql1 = "SELECT C_Country_ID, Name FROM C_Country WHERE IsSummary='N' ORDER BY 1";     //  US first
            IDataReader idr = null;
            String sql2 = "SELECT C_Region_ID, Name FROM C_Region ORDER BY C_Country_ID, Name";
            IDataReader iidr = null;

            try
            {
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    dr = DB.ExecuteReader(sql, null, null);
                    idr = DB.ExecuteReader(sql1, null, null);
                    iidr = DB.ExecuteReader(sql2, null, null);
                    Dispatcher.BeginInvoke(delegate
                    {
                        while (dr.Read())
                        {
                            fCurrency.Items.Add(new KeyNamePair(Util.GetValueOfInt(dr[0].ToString()), dr[1].ToString()));
                        }
                        dr.Close();
                        dr = null;
                        fCurrency.SelectedIndex = 0;
                        while (idr.Read())
                        {
                            fCountry.Items.Add(new KeyNamePair(Util.GetValueOfInt(idr[0].ToString()), idr[1].ToString()));
                        }
                        idr.Close();
                        idr = null;
                        fCountry.SelectedIndex = 0;
                        fRegion.Items.Add(new KeyNamePair(0, " "));
                        while (iidr.Read())
                        {
                            fRegion.Items.Add(new KeyNamePair(Util.GetValueOfInt(iidr[0].ToString()), iidr[1].ToString()));
                        }
                        iidr.Close();
                        iidr = null;
                        fRegion.SelectedIndex = 0;
                        Envs.SetBusyIndicator(false);
                    });
                });

            }
            catch (Exception e1)
            {
                if (dr != null)
                {
                    dr.Close();
                }
                log.Log(Level.SEVERE, "VSetup.dynInit -currency", e1);
                if (idr != null)
                {
                    idr.Close();
                }
                log.Log(Level.SEVERE, "VSetup.dynInit -country", e1);
                if (iidr != null)
                {
                    iidr.Close();
                }
                log.Log(Level.SEVERE, "VSetup.dynInit -region", e1);

            }






        }

        private void buttonLoadAcct_Click(object sender, RoutedEventArgs e)
        {
          bool dlgRes=(bool) fileOpen.ShowDialog();
           if (dlgRes)
           {
               fileopen_OK();
           }
        }
        
        String FclientName = "";
        String FUserClient = "";
        String FUserOrg = "";
        String iclient = "";
        String iuserClient = "";
        String iuserorg = "";
        private bool CreateSetup()
        {
            //	Change critical characters ' => "  \ => /
            fClientName.Text = fClientName.Text.Replace('\'', '"');
            fClientName.Text = fClientName.Text.Replace('\\', '/');
            fOrgName.Text = fOrgName.Text.Replace('\'', '"');
            fOrgName.Text = fOrgName.Text.Replace('\\', '/');
            fUserClient.Text = fUserClient.Text.Replace('\'', '"');
            fUserClient.Text = fUserClient.Text.Replace('\\', '/');
            fUserOrg.Text = fUserOrg.Text.Replace('\'', '"');
            fUserOrg.Text = fUserOrg.Text.Replace('\\', '/');

            FclientName = fClientName.Text;
            FUserClient = fUserClient.Text;
            FUserOrg = fUserOrg.Text;
            iclient = lClientName.Content.ToString();
            iuserClient = lUserClient.Content.ToString();
            iuserorg = lUserOrg.Content.ToString();
            //	Unique Client Name
            
            return true;
        }


        String Status = null;
        private void CreateSetUpNew()
        {

            String SQL = "UPDATE AD_Client SET CreatedBy=0 WHERE Name='" + FclientName + "'";
            //	Unique User Name
            String SQL1 = "UPDATE AD_User SET CreatedBy=0 WHERE Name='" + FUserClient + "'";
            String SQL2 = "UPDATE AD_User SET CreatedBy=0 WHERE Name='" + FUserOrg + "'";
            int count = 0;
            int count1 = 0;
            int count2 = 0;
           
                count = DB.ExecuteQuery(SQL);
                count1 = DB.ExecuteQuery(SQL1);
                count2 = DB.ExecuteQuery(SQL2);
           
            
            if (count != 0)
            {
                Status = iclient;
            }
            if (count1 != 0)
            {   Status =  iuserClient;
            }
            if (count2 != 0)
            {
                Status = iuserorg;
            }
           



        }
      
        KeyNamePair currency = null;
        KeyNamePair pCurrency = null;
        KeyNamePair pRegion = null;
        
       

        //private FileStream GetFile()
        //{
        //    FileStream file = null;

        //    try
        //    {
        //        file = new FileStream(fileOpen.File.Name, FileMode.Open);
        //    }
        //    catch
        //    {
        //    }

        //    if (file == null)
        //    {
        //        buttonLoadAcct.Content = Msg.Translate(Envs.GetContext(), "LoadAccountingValues");
        //    }
          
        //    btnOk.IsEnabled = (file != null);
        //    return file;
        //}
        //bool cfProduct;
        //bool cfBPartner;
        //bool cfProject;
        //bool cfMCampaign;
        //bool cfSRegion;

        String fileName = null;
        protected void fileopen_OK()
        {
           
            buttonLoadAcct.Content = fileOpen.File.Name;
            fileName = fileOpen.File.Name;
            byte[] dataA = null;
            if (fileOpen.File.Exists)//if (openFileDialog.CheckFileExists)
            {
               // int size = _attachment.GetEntryCount();
                Envs.SetBusyIndicator(true);
                FileInfo f = fileOpen.File;
                Stream s = f.OpenRead();
                dataA = ReadFully(s);
                //if (
                DataServiceBasic2.AttachmentEntry obj = new DataServiceBasic2.AttachmentEntry();
                obj.Name = fileOpen.File.Name;
                obj.Data = dataA;
               
                
                var client = Utility.AEnv.GetDataServiceBasic2Client();
                client.UploadAttachmentCompleted += (se, ev) =>
                    {
                        Envs.SetBusyIndicator(false);
                    };
                client.UploadAttachmentAsync(obj);
                client.CloseAsync();
              
            }

         
        }

        public static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[25 * 1024 * 1024];

            if (input.Length > buffer.Length)
            {
                ShowMessage.Warn("FileSizeLimit", true, "", "");
                return null;
            }
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                int offset = 0;
                while ((read = input.Read(buffer, offset, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

       

      


        private string info = "";
      
        

        void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
            this.Dispose();
        }

        private void btnOk_Click_1(object sender, RoutedEventArgs e)
        {
           
            Status = null;
            if (fileName == null)
            {
                //ShowMessage.Error("AccountSetupError", false);
                //return;
            }

            CreateSetup();
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                CreateSetUpNew();
                Dispatcher.BeginInvoke(delegate
                {
                    if (Status == null)
                    {
                        Envs.SetBusyIndicator(true);
                        currency = (KeyNamePair)fCurrency.SelectedItem;
                        pCurrency = (KeyNamePair)fCountry.SelectedItem;
                        pRegion = (KeyNamePair)fRegion.SelectedItem;

                        DataServiceBasic2.ClientSetUp clientSetUp = new DataServiceBasic2.ClientSetUp();

                        clientSetUp.FClientName = fClientName.Text;
                        clientSetUp.FOrgName = fOrgName.Text;                        
                        clientSetUp.FUserClient = fUserClient.Text;
                        clientSetUp.FUserOrg = fUserOrg.Text;
                        clientSetUp.FCity = fCity.Text;
                        clientSetUp.cfProduct = (bool)fProduct.IsChecked;
                        clientSetUp.cfBPartner = (bool)fBPartner.IsChecked;
                        clientSetUp.cfProject = (bool)fProject.IsChecked;
                        clientSetUp.cfMCampaign = (bool)fMCampaign.IsChecked;
                        clientSetUp.cfSRegion = (bool)fSRegion.IsChecked;
                        clientSetUp.C_Country_ID = pCurrency.GetKey();
                        clientSetUp.C_Region_ID = pRegion.GetKey();
                        clientSetUp.currency = new DataServiceBasic2.KeyName();
                        clientSetUp.currency.key = currency.GetKey();
                        clientSetUp.currency.value = currency.GetName();
                        clientSetUp.pCurrency = new DataServiceBasic2.KeyName();
                        clientSetUp.pCurrency.key = pCurrency.GetKey();
                        clientSetUp.pCurrency.value = pCurrency.GetName();
                        clientSetUp.pRegion = new DataServiceBasic2.KeyName();
                        clientSetUp.pRegion.key =  pRegion.GetKey();
                        clientSetUp.pRegion.value = pRegion.GetName();

                        //clientSetUp.currency = new KeyValuePair<int, string>(Convert.ToInt32(currency.Key), currency.Name);// (KeyValuePair<String, int>)fCurrency.SelectedItem;
                        //clientSetUp.pCurrency = new KeyValuePair<int, string>(Convert.ToInt32(pCurrency.Key), pCurrency.Name);//(KeyValuePair<String, int>)fCountry.SelectedItem;
                        //clientSetUp.pRegion = new KeyValuePair<int, string>(Convert.ToInt32(pRegion.Key), pRegion.Name);//(KeyValuePair<String, int>)fRegion.SelectedItem;

                        var client = AEnv.GetDataServiceBasic2Client();
                        //var client =new DataServiceBasic2.DataServicesBasic2Client();
                        client.InitailizeClientSetupCompleted += (Se, ev) =>
                            {
                                //throw new NotImplementedException();
                                Envs.SetBusyIndicator(false);
                                if (ev.Result != null)
                                {
                                    DataServiceBasic2.TenantInfo tInfo = ev.Result;
                                    if (!String.IsNullOrEmpty(tInfo.Log))
                                    {
                                        ShowMessage.Info(tInfo.Log, true, "", "");
                                    }
                                    else
                                    {
                                        StringBuilder text = new StringBuilder();
                                        text.Append(" Tenant Name - " + tInfo.TenantName + "\t\n");
                                        text.Append(" Organization Name - " + tInfo.OrgName + "\t\n");
                                        text.Append(" Admin Role - " + tInfo.AdminRole + "\t\n");
                                        text.Append(" User Role - " + tInfo.UserRole + "\t\n");
                                        text.Append(" Admin Username - " + tInfo.AdminUser + "\t\n");
                                        text.Append(" Admin User Password - " + tInfo.AdminUserPwd + "\t\n");
                                        text.Append(" Org Username - " + tInfo.OrgUser + "\t\n");
                                        text.Append(" Org User Password - " + tInfo.OrgUserPwd + "\t\n");
                                        TenantInfo win = new TenantInfo();
                                        win.SetData(text.ToString());
                                        win.Show();
                                    }
                                }
                              //  {
                              //      ShowMessage.Info(ev.Result, true, "", "");
                              //  }
                              // 
                              
                              //  ShowMessage.Info("VSetup", true, info, "");
                                this.IsEnabled = true;
                               // gridProgress.Visibility = Visibility.Collapsed;

                            };

                        client.InitailizeClientSetupAsync(clientSetUp, fileName, (Dictionary<string, string>)Envs.GetCtx().GetMap());
                        client.CloseAsync();
                    }
                    else
                    {
                        ShowMessage.Error("NotUnique", true, Status);
                    }
                });
                
            });



         
        }

     

      
        
    }
}
